package com.platform.qujia.controller;

import com.google.gson.Gson;
import com.platform.qujia.dao.StationMapper;
import com.platform.qujia.param.response.StationInfoResponse;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.MapHelper;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.exception.EndingException;
import com.platform.qujia.utils.tonglianpay.TLPayParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * <Title> EnterpriseController </Title>
 * <Description> 油企下油站各信息控制层 </Description>
 * <Date>2021年10月28日</Date>
 */

@RestController
@Api(tags = "油企下油站各信息接口")
//@QuJiaRequest()
@CrossOrigin
public class EnterpriseController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(EnterpriseController.class);
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private PosMachineService posMachineService;
    @Autowired
    private SysUserService sysUserService;

    @Resource
    private StationMapper stationMapper;

    @Autowired
    private ReductionActivityService reductionActivityService;
    /*
     * 获取油企信息
     * @param enterpriseId
     * @return
     */
    @GetMapping( value = "/selectEnterpriseInfo")
    @ApiOperation(value = "获取油企信息", httpMethod = "GET", notes = "获取油企信息")
    public String selectEnterpriseInfo(@ApiParam(value = "油站ID", required = true) @RequestParam Integer enterpriseId){
        Gson gson = new Gson();
        ResultData resultData = null;
        if(enterpriseId !=null){
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            resultData = ResultData.success(enterprise);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return  gson.toJson(resultData);
    }


    @GetMapping( value = "/selectStationInfo")
    @ApiOperation(value = "获取油站信息", httpMethod = "GET", notes = "获取油站信息")
    public String selectStationInfo(@ApiParam(value = "油站ID", required = true) @RequestParam Integer stationId){
        Gson gson = new Gson();
        ResultData resultData = null;
        if(stationId !=null){
            Station station = enterpriseService.selectStationById(stationId);
            resultData = ResultData.success(station);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return  gson.toJson(resultData);
    }

    /*
     * 获取油品列表信息
     * @param enterpriseId
     * @return
     */
    @GetMapping( value = "/selectOilInfoList")
    @ApiOperation(value = "获取油品列表信息", httpMethod = "GET", notes = "获取油品列表信息")
    public String selectOilInfoList(){
        Gson gson = new Gson();
        ResultData resultData = null;
        resultData = ResultData.success(enterpriseService.selectOilInfoList());
        return  gson.toJson(resultData);
    }

    /*
     * 获取油企下油站信息列
     * @param enterpriseId
     * 适用于小程序3.1.18之上 替代selectStaInfoList接口
     * @return
     */
    @ApiOperation(value = "获取油企下油站信息列", httpMethod = "GET", notes = "获取油企下油站信息列")
    @GetMapping( value = "/appletSelectStationList")
    public String appletSelectStationList(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId, String stationLongitude,String stationLatitude,Integer pageNum,Integer pageSize){
        Gson gson = new Gson();
        Map<String, Object> resultMap = new HashMap<>();
        ResultData resultData = null;

        if(enterpriseId !=null){
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);

            List<Station> stationList = enterpriseService.selectStaInfoList(station);
            if (Objects.nonNull(stationList)){
//                for (int i = 0; i < stationList.size(); i++) {
//                    String activities = reductionActivityService.selectReductionActivity(stationList.get(i).getStationId());
//                    if (Objects.nonNull(activities)) stationList.get(i).setActivities(activities);
//                }
            }
            if(StringUtils.isNotBlank(stationLatitude) && StringUtils.isNotBlank(stationLongitude)){
                String coordinate = stationLatitude + "," + stationLongitude;
                //根据地址坐标计算距离
                stationList = computeStaDistance(coordinate, stationList);
            }
            Enterprise tmpEnterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);

            resultMap.put("stationList", stationList);
            resultMap.put("appletShowOilNamePrice",tmpEnterprise.getAppletShowOilNamePrice());

            resultData = ResultData.success(resultMap);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return  gson.toJson(resultData);
    }


    /*
     * 获取油企下油站信息列
     * @param enterpriseId
     * @return
     */
    @ApiOperation(value = "获取油企下油站信息列", httpMethod = "GET", notes = "获取油企下油站信息列")
    @GetMapping( value = "/selectStaInfoList")
    public String selectStaInfoList(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId, String stationLongitude,String stationLatitude,Integer pageNum,Integer pageSize){
        Gson gson = new Gson();
        ResultData resultData = null;
        if(enterpriseId !=null){
            Station station = new Station();
            station.setStationLatitude(stationLatitude);
            station.setStationLongitude(stationLongitude);
            station.setEnterpriseId(enterpriseId);
            List<Station> stationList = enterpriseService.selectStaInfoList(station);
            if(StringUtils.isNotBlank(stationLatitude) && StringUtils.isNotBlank(stationLongitude)){
                String coordinate = stationLatitude + "," + stationLongitude;
                //根据地址坐标计算距离
                stationList = computeStaDistance(coordinate, stationList);
            }
            resultData = ResultData.success(stationList);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return  gson.toJson(resultData);
    }

    //计算距离
    public List<Station> computeStaDistance(String coordinate, List<Station> stationList){
        List<Station> stationInfoList = new ArrayList<>();
        if(stationList!=null && stationList.size() > 0){
            for (Station station : stationList) {
                Station stationInfoResponse =new Station();
                String longitude = station.getStationLongitude();
                String latitude = station.getStationLatitude();
                if(StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(coordinate)){
                    String distanceData = latitude+","+longitude;
                    double distance = MapHelper.GetPointDistance(coordinate, distanceData);
                    Double format = Double.parseDouble(String.format("%.1f", distance));
                    //计算距离 展示距离小于5公里以内的站
                    //if(format<=5){
                    //stationInfoResponse.setCity(stationInfo.getCity());
                    stationInfoResponse.setStationId(station.getStationId());
                    stationInfoResponse.setStationName(station.getStationName());
                    stationInfoResponse.setRegionData(station.getRegionData());
                    stationInfoResponse.setDetailRegionData(station.getDetailRegionData());
                    stationInfoResponse.setHeadImg(station.getHeadImg());
                    stationInfoResponse.setIsAlipayFlag(station.getIsAlipayFlag());
                    stationInfoResponse.setEnterpriseId(station.getEnterpriseId());
                    stationInfoResponse.setStationLatitude(station.getStationLatitude());
                    stationInfoResponse.setStationLongitude(station.getStationLongitude());
                    stationInfoResponse.setOilList(station.getOilList());
                    stationInfoResponse.setDistance(format);
                    stationInfoList.add(stationInfoResponse);
                    //}
                }
            }
            //排序
            stationInfoList.sort((((o1, o2) -> o1.getDistance().compareTo(o2.getDistance()))));
        }
        return stationInfoList;
    }

    /*
     * 获取油站下油枪信息列
     * @param stationId 油站ID
     * @return
     */
    @ApiOperation(value = "获取油站下油枪信息列", httpMethod = "GET", notes = "获取油站下油枪信息列")
    @GetMapping( value = "/selectStaOilGunList")
    public String selectStaOilGunList(@ApiParam(value = "油站ID", required = true) @RequestParam Integer stationId,
                                      @ApiParam(value = "用户名", required = false) String userId,@ApiParam(value = "设备号", required = false)String deviceNo){
        logger.info("获取油枪列表参数：油站ID："+ stationId + "; 加油员userID: " + userId +"; 设备号:"+deviceNo);
        if (StringUtils.isNotBlank(userId)) {
            String[] split = userId.split("&");
            userId = split[0];
        }
        Gson gson = new Gson();
        ResultData resultData = null;
        if(stationId !=null){
            Map<String, Object> resultMap = new HashMap<>();
            Station station = enterpriseService.selectStationById(stationId);
            if(station !=null){
                //查询设备
                StationDeviceManager deviceManager=null;
                if(StringUtils.isNotEmpty(deviceNo)){
                    deviceManager=new StationDeviceManager();
                    deviceManager.setStationId(stationId);
                    deviceManager.setDeviceNo(deviceNo);
                    deviceManager = posMachineService.getStationDeviceManager(deviceManager);

                }


                StaOilGun staOilGun = new StaOilGun();
                staOilGun.setStationId(stationId);
                String imgUrl = station.getImgUrl();
                if(StringUtils.isNotBlank(imgUrl)){
                    List<String> imgList = Arrays.asList(imgUrl.split(","));
                    resultMap.put("imgList", imgList);
                }

                resultMap.put("employeeAppletFlag", station.getEmployeeAppletFlag());
                resultMap.put("stationNotice", station.getStationNotice());
                resultMap.put("stationPayPush", station.getStationPayPush());
                //是否启用  必须扫加油员扫码
                if(StringUtils.isNotBlank(station.getEmployeeAppletFlag()) && "1".equals(station.getEmployeeAppletFlag()) && !StringUtils.isNotBlank(userId)){
                    resultData = ResultData.error(CodeMsg.SCAN_EMPLOYEE);
                }else {
                    //获取油枪列表
                    List<StaOilGun> staOilGunList = new ArrayList<>();
                    staOilGunList  = enterpriseService.selectStaOilGunList(staOilGun);
                    resultMap.put("staOilGunList", staOilGunList);
                    if(StringUtils.isNotBlank(userId)){
                        //如果传入用户名，则查询该用户负责的枪
//                        SysUser sysUser = posMachineService.selectUserByUserId(userId);

                        SysUser sysUser = posMachineService.selectUserByUserIdCache(userId);

                        if(sysUser !=null){
                            if(sysUser.getStationId() !=null && sysUser.getStationId().equals(stationId.toString())){
                                if(StringUtils.isNotBlank(sysUser.getGun())){
                                    staOilGun.setGunList(sysUser.getGun().split(","));
                                    if(deviceManager!=null&&StringUtils.isNotEmpty(deviceManager.getGunNo())){
                                        List<String> list = Arrays.asList(deviceManager.getGunNo().split(","));
                                       /* list.retainAll(Arrays.asList(sysUser.getGun().split(",")));*/
                                        String[] gunList = list.stream().toArray(String[]::new);
                                        staOilGun.setGunList(gunList);
                                    }

                                    //staOilGunList = enterpriseService.selectStaOilGunList(staOilGun);
                                    staOilGunList = enterpriseService.selectStaOilGunListCache("" + stationId, userId, staOilGun);


                                    if(null != staOilGunList && staOilGunList.size()>0){
                                        resultMap.put("staOilGunList", staOilGunList);
                                        resultMap.put("isTube",station.getIsTube());
                                        resultData = ResultData.success(resultMap);
                                    }else {
                                        resultData = ResultData.error(CodeMsg.NO_USER_HAVE_GUN);
                                    }
                                }else {
                                    resultData = ResultData.error(CodeMsg.NO_USER_HAVE_GUN);
                                    if(deviceManager!=null&&StringUtils.isNotEmpty(deviceManager.getGunNo())){
                                        List<String> list = Arrays.asList(deviceManager.getGunNo().split(","));
                                        /* list.retainAll(Arrays.asList(sysUser.getGun().split(",")));*/
                                        String[] gunList = list.stream().toArray(String[]::new);
                                        staOilGun.setGunList(gunList);
                                        //staOilGunList = enterpriseService.selectStaOilGunList(staOilGun);
                                        staOilGunList = enterpriseService.selectStaOilGunListCache("" + stationId, "", staOilGun);
                                        resultMap.put("staOilGunList", staOilGunList);
                                        resultData = ResultData.success(resultMap);
                                    }
                                }
                            }else{
                                resultData = ResultData.error(CodeMsg.USER_STATION_ERROR);
                            }
                        }else {
                            resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
                        }
                    }else {
                        if(deviceManager!=null&&StringUtils.isNotEmpty(deviceManager.getGunNo())){
                            List<String> list = Arrays.asList(deviceManager.getGunNo().split(","));
                            /* list.retainAll(Arrays.asList(sysUser.getGun().split(",")));*/
                            String[] gunList = list.stream().toArray(String[]::new);
                            staOilGun.setGunList(gunList);
                            //staOilGunList = enterpriseService.selectStaOilGunList(staOilGun);
                            staOilGunList = enterpriseService.selectStaOilGunListCache("" + stationId, "", staOilGun);
                            resultMap.put("staOilGunList", staOilGunList);
                        }


                        resultData = ResultData.success(resultMap);
                    }
                }
            }else {
                resultData = ResultData.error(CodeMsg.STATION_NULL_INFO);
            }
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return  gson.toJson(resultData);
    }



    /*
     * 获取油企下油站信息列
     * @param enterpriseId
     * 适用于小程序3.1.18之上 替代selectStaInfoList接口
     * @return
     */
    @ApiOperation(value = "获取加油员列表", httpMethod = "GET", notes = "获取加油员列表")
    @GetMapping( value = "/selectSysUserList")
    public String selectSysUserList(
            @ApiParam(value = "油站id")  String stationId,
            @ApiParam(value = "油企id")  String enterpriseId
    ) {
        try {
            if (stationId == null && enterpriseId == null) {
                throw new EndingException("油企id和油站id至少传一个");
            }
            List<SysUser> sysUserList = sysUserService.selectSysUserList(
                    SysUser.builder()
                            .delFlag(String.valueOf(0))
                            .enterpriseId(enterpriseId)
                            .stationId(stationId)
                            .build()
            );
            return ResultData.successJson(sysUserList);

        } catch (EndingException e) {
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/createOrder-", e);
            return ResultData.errorJson(e.getMessage());
        }
    }

    @ApiOperation(value = "获取pos机订单默认时段", httpMethod = "GET", notes = "获取pos机订单默认时段")
    @GetMapping( value = "/selectPosDefaultQueryPeriod")
    public String selectPosDefaultQueryPeriod(@ApiParam(value = "油站id")  String stationId){
        Gson gson = new Gson();
        if(StringUtils.isEmpty(stationId)){
            return  gson.toJson(ResultData.error("stationId不能为空"));
        }
        Station station = stationMapper.selectStationById(Integer.parseInt(stationId));
        String posDefaultQueryPeriod = station.getPosDefaultQueryPeriod();
        Map<String,String> result=new HashMap<>();
        SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy-MM-dd");
        String startTime = dateFormat2.format(new Date())+" 00:00:00";
        String endTime = dateFormat1.format(new Date());

        try{
            if(StringUtils.isNotEmpty(station.getPosDefaultQueryPeriod())){
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HALF_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 00:30:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MINUTE, -30);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
                if(posDefaultQueryPeriod.equals(Station.POSDEFAULTQUERYPERIOD_LAST_HOUR)){
                    if(dateFormat1.parse(dateFormat2.format(new Date())+" 01:00:00").before(new Date())){
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.HOUR, -1);
                        startTime = dateFormat1.format(calendar.getTime());
                    }
                }
            }
        }catch (Exception e){
           return  gson.toJson(ResultData.error(e.getMessage()));
        }
        result.put("startTime",startTime);
        result.put("endTime",endTime);
        return ResultData.successJson(result);
    }
}
